from _decimal import Decimal

from django.db import transaction
from django.utils import timezone
from django_redis import get_redis_connection
from rest_framework import serializers

from goods.models import SKU
from orders.models import OrderInfo, OrderGoods


class CartSKUSerializer(serializers.ModelSerializer):
    count=serializers.IntegerField()

    class Meta:
        model = SKU
        fields = ('id', 'name', 'default_image_url', 'price', 'count')


class OrderSettlementSerializer(serializers.Serializer):
    """
    订单结算数据序列化器
    """
    freight = serializers.DecimalField(label='运费', max_digits=10, decimal_places=2)
    skus = CartSKUSerializer(many=True)


class SaveOrderSerializer(serializers.ModelSerializer):

    class Meta:
        model = OrderInfo
        fields = ('address', 'pay_method', 'order_id')
        extra_kwargs = {
            'address': {'write_only': True,
                        'required':True},
            'pay_method': {
                'write_only': True,
                'required': True
            },
            'order_id': {
                'read_only': True,

            }
        }

    def create(self, validated_data):
        '''201811211053+user.id'''
        user=self.context['request'].user
        user_id=user.id
        order_id = timezone.now().strftime('%Y%m%d%H%M%S') + ('%09d' % user_id)
        print(order_id)
        address=validated_data['address']
        # freight=validated_data['freight']
        pay_method=validated_data['pay_method']
        total_count = 0
        total_amount = 0
        with transaction.atomic():
            # 创建一个保存点
            save_id = transaction.savepoint()
        try:
            order=OrderInfo.objects.create(
                order_id=order_id,
                user=user,
                address=address,
                total_count=total_count,
                total_amount=total_amount,
                freight=Decimal('10'),
                pay_method=pay_method,
                status=OrderInfo.ORDER_STATUS_ENUM["UNPAID"] if pay_method==OrderInfo.PAY_METHODS_ENUM["ALIPAY"] else OrderInfo.ORDER_STATUS_ENUM["UNSEND"]
            )
            # 拿到redis中商品数据
            redis_connect=get_redis_connection('cart')
            redis_dict = redis_connect.hgetall('cart_%s' % user_id)
            cart_select = redis_connect.smembers('cart_selected_%s' % user_id)
            cart_dict={}
            for sku_id in cart_select:
                cart_dict[int(sku_id)]=int(redis_dict[sku_id])
            goods=SKU.objects.filter(id__in=cart_dict.keys())
            for good in goods:
                # 检查库存
                if good.stock < cart_dict[good.id]:
                    raise serializers.ValidationError('库存不够')
                good.stock-=cart_dict[good.id]
                good.sales+=cart_dict[good.id]
                '''count 是数量'''
                '''amount　金额 '''
                total_count+=cart_dict[good.id]
                total_amount+=good.price
                order.total_count=total_count
                order.total_amount=total_amount
                OrderGoods.objects.create(
                    order=order,
                    sku=good,
                    count=cart_dict[good.id],
                    price=good.price,
                )
        except Exception as e:
            transaction.savepoint_rollback(save_id)
            raise
        # 清除redis已经结算的商品
        '''pl.hdel('cart_%s' % user.id, *cart_selected)
            pl.srem('cart_selected_%s' % user.id, *cart_selected)'''
        for sku_id in cart_select:
            redis_connect.hdel('cart_%s' % user_id,sku_id)
            redis_connect.srem('cart_selected_%s' % user_id,sku_id)
        order.save()
        return order
